import React, { useState } from 'react'
import { Form, Input, Button, Card, Space, Modal, App, Image } from 'antd'
import {
  UserOutlined,
  LockOutlined,
  MailOutlined,
  createFromIconfontCN,
} from '@ant-design/icons'
import { useLocation, useNavigate } from 'react-router-dom'
import { userStore } from '../stores'
import { LoginFormValues } from '../types'
import '../styles/login.css'
import { useRequest } from 'alova/client'

const Login: React.FC = () => {
  const { message } = App.useApp()
  const [loading, setLoading] = useState(false)
  const [loginError, setLoginError] = useState<
    Error | { code: number; msg: string } | null
  >(null)
  const [registerVisible, setRegisterVisible] = useState(false)
  const [registerLoading, setRegisterLoading] = useState(false)
  const [registerForm] = Form.useForm()
  const navigate = useNavigate()

  // 验证码相关状态
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const redirectTo = searchParams.get('redirect') || '/'

  // 打开注册弹窗
  const showRegisterModal = () => {
    setRegisterVisible(true)
  }

  // 关闭注册弹窗
  const handleRegisterCancel = () => {
    setRegisterVisible(false)
    registerForm.resetFields()
  }

  // 处理注册提交
  const handleRegisterSubmit = async () => {
    try {
      await registerForm.validateFields()
      setRegisterLoading(true)

      // 模拟注册API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      // 这里应该调用实际的注册API，但我们不修改src/apis中的文件
      // 所以这里只是模拟一个成功的注册
      message.success('注册成功！请使用新账号登录')
      setRegisterVisible(false)
      registerForm.resetFields()
    } catch (error) {
      console.error('注册表单验证失败:', error)
    } finally {
      setRegisterLoading(false)
    }
  }

  const {
    loading: captchaLoading,
    send: fetchCaptcha,
    data: captchaData,
  } = useRequest(Apis.auth.LoginGetCodeImg()).onError((e) => {
    console.log(captchaData)
    message.error(e.error.msg)
  })

  const onFinish = async (values: LoginFormValues) => {
    setLoading(true)
    try {
      // 使用MobX store的login方法，传入验证码
      const res = await userStore.login(
        values.username,
        values.password,
        values.code,
        captchaData.headers.img_code
      )

      if (res.success) {
        message.success('登录成功！')
        // 登录成功后判断是否有redirecTo，若有，跳转，若无，跳转到首页
        if (redirectTo) {
          navigate(redirectTo)
        } else {
          navigate('/')
        }
      } else {
        setLoginError(res.error!)
        // 登录失败时刷新验证码
        fetchCaptcha()
      }
    } catch (error) {
      setLoginError(error as Error)
      // 登录失败时刷新验证码
      fetchCaptcha()
    } finally {
      setLoading(false)
    }
  }

  const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/c/font_4865374_jels87ofda.js',
  })

  return (
    <div className="min-h-screen flex items-center justify-center bg-defaultBg w-full login-container">
      <div className="w-full max-w-md px-4 z-1">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="flex justify-center mb-4">
            {/* <ThunderboltFilled className="text-5xl text-primary" /> */}
            <Space>
              <IconFont
                type="icon-chunshuizhuangzhi"
                style={{ fontSize: '88px' }}
              />
            </Space>
          </div>
          <h1 className="text-2xl font-bold text-gray-800">
            郑水净界全流程管理系统
          </h1>
          <p className="text-gray-500 mt-2">欢迎登录管理平台</p>
        </div>

        {/* 登录卡片 */}
        <Card
          className="shadow-lg rounded-lg overflow-hidden"
          variant="borderless"
        >
          <h2 className="text-xl font-medium mb-6 text-center">账号登录</h2>
          <Form
            name="login"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            size="large"
            layout="vertical"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input
                prefix={<UserOutlined className="text-gray-400" />}
                placeholder="用户名"
                className="rounded-md"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password
                prefix={<LockOutlined className="text-gray-400" />}
                placeholder="密码"
                className="rounded-md"
              />
            </Form.Item>
            <Form.Item
              name="code"
              rules={[{ required: true, message: '请输入验证码!' }]}
              className="mb-4"
            >
              <div className="flex items-center gap-2">
                <Input
                  prefix={<LockOutlined className="text-gray-400" />}
                  placeholder="验证码"
                  className="rounded-md"
                  style={{ flex: 1 }}
                />
                {captchaLoading ? (
                  <div
                    className="rounded-md bg-gray-200 flex items-center justify-center cursor-pointer"
                    onClick={fetchCaptcha}
                    style={{ height: '32px', width: '100px' }}
                  >
                    加载验证码
                  </div>
                ) : captchaData ? (
                  <Image
                    className="rounded-md cursor-pointer"
                    src={
                      captchaData.data
                        ? (captchaData.data as unknown as string)
                        : undefined
                    }
                    alt="验证码"
                    preview={false}
                    onClick={fetchCaptcha}
                    style={{ height: '32px' }}
                  />
                ) : (
                  <div
                    className="rounded-md bg-gray-200 flex items-center justify-center cursor-pointer"
                    onClick={fetchCaptcha}
                    style={{ height: '32px', width: '100px' }}
                  >
                    验证码加载失败
                  </div>
                )}
              </div>
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="w-full rounded-md h-10"
                loading={loading}
              >
                登录
              </Button>
            </Form.Item>
            {loginError && (
              <Form.Item>
                <div className="text-red-500">
                  {(loginError as { msg?: string })?.msg ||
                    '登录失败，请检查用户名和密码'}
                </div>
              </Form.Item>
            )}
            <Form.Item>
              <div className="flex justify-between items-center">
                <Form.Item noStyle>
                  <Button
                    type="text"
                    className="!text-info hover:!text-info/70"
                    onClick={showRegisterModal}
                  >
                    注册账号
                  </Button>
                </Form.Item>
                <Form.Item noStyle>
                  <Button
                    type="text"
                    className="!text-info hover:!text-info/70"
                    href="#"
                  >
                    忘记密码？
                  </Button>
                </Form.Item>
              </div>
            </Form.Item>
          </Form>
        </Card>

        {/* 页脚 */}
        <div className="mt-6 text-center text-gray-500 text-sm">
          © {new Date().getFullYear()} 郑水净界@郑州高新水务工程有限公司
          版权所有
        </div>
      </div>

      {/* 注册弹窗 */}
      <Modal
        title="注册新账号"
        open={registerVisible}
        onCancel={handleRegisterCancel}
        footer={null}
        width={window.innerWidth < 768 ? '90%' : 520}
        destroyOnClose
        className="register-modal"
      >
        <Form
          form={registerForm}
          name="register"
          layout="vertical"
          size="large"
          onFinish={handleRegisterSubmit}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名!' },
              { min: 3, message: '用户名至少3个字符' },
            ]}
          >
            <Input
              prefix={<UserOutlined className="text-gray-400" />}
              placeholder="请输入用户名"
              className="rounded-md"
            />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '请输入有效的邮箱地址!' },
            ]}
          >
            <Input
              prefix={<MailOutlined className="text-gray-400" />}
              placeholder="请输入邮箱"
              className="rounded-md"
            />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码!' },
              { min: 6, message: '密码至少6个字符' },
            ]}
            hasFeedback
          >
            <Input.Password
              prefix={<LockOutlined className="text-gray-400" />}
              placeholder="请输入密码"
              className="rounded-md"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={['password']}
            hasFeedback
            rules={[
              { required: true, message: '请确认密码!' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'))
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="text-gray-400" />}
              placeholder="请确认密码"
              className="rounded-md"
            />
          </Form.Item>

          <Form.Item className="mb-0">
            <div className="flex justify-end gap-2">
              <Button onClick={handleRegisterCancel}>取消</Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={registerLoading}
              >
                注册
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Login
